#include "TcpServer.h"
#include "UdpServer.h"
#include "Thread.h"

class Buffer
{
public:
    char c[1024];
};

struct HandleTask : public FL::Thread
{
    TcpClient client;
    Buffer buf;

    HandleTask(const TcpClient &client) : client(client)
    {
        LOGI("a new task create to handle %s :%d", client.IP(), client.Port());
    };
    void Run()
    {
        while (1)
        {
            int recvLen = client.Recv<Buffer>(buf);
            // LOGI("recv len is %d break",recvLen);

            if (recvLen > 0)
            {
                LOGI("recv %s", buf.c);
            }
            else if (recvLen == 0)
            {
                LOGI("Current Socket %s %d disconnected ", client.IP(), client.Port());
                break;
            }
            else if (recvLen < 0)
            {
                LOGI("Current Socket %s %d disconnected ", client.IP(), client.Port());
                break;
            }
        }
    }
};

void TestUdpServer()
{
    Buffer buf;

    UdpServer server;
    UdpServer::Desc desc;
    desc.port = 1234;
    desc.sAddr = inet_addr("0");
    if (!server.Create(desc))
    {
        LOGI("create failed", "");
    }

    while (1)
    {

        UdpClient client;
        int len = server.RecvFrom<Buffer>(buf, client);
        LOGI("recv from %s %d: %s", client.IP(), client.Port(), buf.c);
    }
}

void TestTcpServer()
{
    TcpServer::Desc desc;
    desc.port = 1234;
    TcpServer server;
    server.Create(desc);
    while (1)
    {
        TcpClient client = server.Accept();
        LOGI("recv a new client", "");
        HandleTask task(client);
        task.Start();
    };
}
int main()
{
    // TestUdpServer();

    TestTcpServer();

    return 0;
}